package com.boyinet.data.export.fx.controller;

import com.boyinet.data.export.ExportApplication;
import com.boyinet.data.export.service.ExportDataService;
import com.boyinet.data.export.vo.SearchParam;
import com.browniebytes.javafx.control.DateTimePicker;
import de.felixroske.jfxsupport.FXMLController;
import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.stage.FileChooser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;

@FXMLController
public class IndexFxmlController {

    private final ExportDataService exportDataService;

    @FXML
    TextField ids;

    @FXML
    DateTimePicker startTime;

    @FXML
    DateTimePicker endTime;

    public IndexFxmlController(ExportDataService exportDataService) {
        this.exportDataService = exportDataService;
    }


    public void export() throws IOException {
        String text = ids.getText();
        if (!text.isEmpty()) {
            String[] idArray = text.split(",");

            LocalDateTime start = startTime.dateTimeProperty().get();
            LocalDateTime end = endTime.dateTimeProperty().get();

            SearchParam searchParam = new SearchParam();
            searchParam.setIds(Arrays.asList(idArray));
            searchParam.setStartTime(Date.from(start.atZone(ZoneId.systemDefault()).toInstant()));
            searchParam.setEndTime(Date.from(end.atZone(ZoneId.systemDefault()).toInstant()));
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("文件保存");
            File file = fileChooser.showOpenDialog(ExportApplication.getStage());
            if (file != null) {
                exportDataService.export(new FileOutputStream(file), searchParam);
            }
        }

    }
}
